package com.aiit.service.Impl;

import com.aiit.mapper.RoleMapper;
import com.aiit.mapper.UserMapper;
import com.aiit.mapper.UserRoleMapper;
import com.aiit.pojo.Role;
import com.aiit.pojo.User;
import com.aiit.service.UserService;
import com.aiit.util.SaltUtil;
import com.aiit.vo.PageResultVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: LuTao
 * @Date: 2022/05/04/9:00
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void register(User user) {
        //处理业务调用Mapper
        //1.生成随机盐
        String salt = SaltUtil.getSalt(8);
        //2.将随机盐保存到数据
        user.setSalt(salt);
        //3.明文密码进行md5+salt+hash散列
        Md5Hash md5Hash=new Md5Hash(user.getPassword(),salt,1024);
        user.setPassword(md5Hash.toHex());
        int insert = userMapper.insert(user);
    }

    @Override
    public List<Role> findRolesByUsername(String username) {
        return userMapper.findRolesByUsername(username);
    }

    @Override
    public PageResultVo<User> getByCondition(Long page, Long limit, String username, String role, String locked, String startTime, String endTime) {
        PageResultVo<User> pageResultVo = new PageResultVo<>();
        List<User> userList = userMapper.getAllByCondition((page - 1) * limit, limit, username, role, locked, startTime, endTime);
        userList.forEach(user -> {
            user.setRoles(findRolesByUsername(user.getUsername()));
        });
        pageResultVo.setRecords(userList);
        pageResultVo.setTotal(userMapper.getCountByCondition(username,role,locked,startTime,endTime));
        return pageResultVo;
    }

    @Override
    public void saveUser(User user, String[] role) {

    }

    @Override
    public void updateUser(User user, String[] role) {

    }

    @Override
    public void deleteUser(String id) {

    }
}
